package com.foxchen.ddns.service.impl.v6;


import com.foxchen.ddns.service.IpGetServiceV6;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

@Slf4j
@Component("network-get")
public class LocalNetWorkV6ServiceImpl implements IpGetServiceV6 {

    @Override
    @SneakyThrows
    public String getIp(String url) {
        List<String> ipV6List = new ArrayList<>();
        // 获取所有网络接口
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            // 确保网络接口已启用
            if (networkInterface.isUp()) {
                // 获取与此网络接口绑定的InetAddress
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();

                while (addresses.hasMoreElements()) {
                    InetAddress inetAddress = addresses.nextElement();
                    // 检查是否为IPv6地址
                    if (inetAddress instanceof Inet6Address) {
                        String hostAddress = inetAddress.getHostAddress();
                        if(StringUtils.isNotBlank(hostAddress) && hostAddress.contains("%")){
                            hostAddress = hostAddress.split("%")[0];
                            log.info("get ipv6 addr:{} , newAddr:{}",inetAddress.getHostAddress(),hostAddress);
                        }

                        if(!isMatch(hostAddress)){
                            log.info("hostAddress not match,{}",hostAddress);
                            continue;
                        }

                        Pattern pattern = Pattern.compile("^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");
                        boolean isValid = pattern.matcher(hostAddress).matches();
                        log.info("get ipv6 addr:{},isMatch:{}",hostAddress,isValid);
                        if(isValid){
                            ipV6List.add(hostAddress);
                        }
                    }
                }
            }
        }
        log.info("ipV6List={}",ipV6List);
        if(CollectionUtils.isEmpty(ipV6List)){
            return null;
        }

        // 最长的ipv6
        return ipV6List.stream().max(Comparator.comparing(String::length)).orElse(StringUtils.EMPTY);
    }

    private boolean isMatch(String ipV6) {
        String firstPrefix = ipV6.split(":")[0];
        int parseInt = Integer.parseInt(firstPrefix,16);

        return parseInt >= 0x2000 && parseInt <= 0x3FFF;
    }
}
